<script setup lang="ts">
import { useCopy } from '@/composable/copy';
import { useValidation } from '@/composable/validation';
import { isNotThrowing } from '@/utils/boolean';
import { withDefaultOnError } from '@/utils/defaults';

const encodeInput = ref('https://www.tremblingboy.cn/');
const encodeOutput = computed(() => withDefaultOnError(() => encodeURIComponent(encodeInput.value), ''));

const encodedValidation = useValidation({
  source: encodeInput,
  rules: [
    {
      validator: value => isNotThrowing(() => encodeURIComponent(value)),
      message: '解析失败',
    },
  ],
});

const { copy: copyEncoded } = useCopy({ source: encodeOutput, text: 'Encoded string copied to the clipboard' });

const decodeInput = ref('https%3A%2F%2Fwww.tremblingboy.cn%2F');
const decodeOutput = computed(() => withDefaultOnError(() => decodeURIComponent(decodeInput.value), ''));

const decodeValidation = useValidation({
  source: encodeInput,
  rules: [
    {
      validator: value => isNotThrowing(() => decodeURIComponent(value)),
      message: '解析失败',
    },
  ],
});

const { copy: copyDecoded } = useCopy({ source: decodeOutput, text: 'Decoded string copied to the clipboard' });
</script>

<template>
  <c-card title="编码">
    <c-input-text
      v-model:value="encodeInput"
      label="编码前的 Url"
      :validation="encodedValidation"
      multiline
      autosize
      placeholder="需要编码的 Url"
      rows="2"
      mb-3
    />

    <c-input-text
      label="编码后的 Url"
      :value="encodeOutput"
      multiline
      autosize
      readonly
      placeholder="编码后的 Url"
      rows="2"
      mb-3
    />

    <div flex justify-center>
      <c-button @click="copyEncoded()">
        复制
      </c-button>
    </div>
  </c-card>
  <c-card title="解码">
    <c-input-text
      v-model:value="decodeInput"
      label="解码前的 Url"
      :validation="decodeValidation"
      multiline
      autosize
      placeholder="需要解码的 Url"
      rows="2"
      mb-3
    />

    <c-input-text
      label="解码后的 Url"
      :value="decodeOutput"
      multiline
      autosize
      readonly
      placeholder="解码后的 Url"
      rows="2"
      mb-3
    />

    <div flex justify-center>
      <c-button @click="copyDecoded()">
        复制
      </c-button>
    </div>
  </c-card>
</template>
